const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function http(url,callBack,data,method='GET'){
    wx.request({
      url: url,
      method: method,
      data: data,
      header:{
        'content-type': 'application/json'
      },
      success:function(res){
        callBack(res)
      },
      fail:function(res){
        console.log(res.errMsg)
      }
    })
}
function login(callback = '', from_uid='') {
  var that = this;
  if (wx.getExtConfig) {
    wx.getExtConfig(
      {
        success: function (res) {
          wx.login({
            success: function (res) {
              var code = res.code;
              if (code) {
                console.log('获取用户登录凭证：' + code);
                wx.getUserInfo({
                  success: function (res) {
                    wx.request({
                      //用户登陆URL地址
                      url: "https://chengzi.h.miniprogram.xin/index.php?r=user/login",
                      method: "POST",
                      header: { "content-type": "application/x-www-form-urlencoded" },
                      data: {
                        code: code,
                        encryptedData: res.encryptedData,
                        iv: res.iv,
                        from_uid:from_uid
                      },
                      success: function (res) {     
                        //设置用户缓存
                        wx.setStorageSync("openid", res.data.data.openid);
                        wx.setStorageSync("name", res.data.data.uname);
                        wx.setStorageSync("uid", res.data.data.u_id);
                        callback(res)
                      },
                      fail: function (res) {
                        console.log(res)
                        console.log('设置用户缓存失败');
                        callback(res)
                      }
                    })
                  },
                  fail: function (res) {
                    console.log(res, '失败')
                    callback(res)
                  }
                })
              } else {
                console.log('获取用户登录状态失败：' + res.errMsg);
              }
            },
            fail: function () {
              console.log('网络错误');
            },
          })
        }
      })
  }
}




module.exports = {
  formatTime: formatTime,
  http:http,
  login: login
}
